package com.weiyi.weiman.api;

import com.weiyi.weiman.annotation.Log;
import com.weiyi.weiman.domain.dto.ResultInfo;
import com.weiyi.weiman.exception.APIException;
import com.weiyi.weiman.exception.TokenException;
import com.weiyi.weiman.service.user.UserBalanceService;
import com.weiyi.weiman.service.user.UserService;
import com.weiyi.weiman.utils.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author zhang
 * @Date 2021/5/14 下午10:51
 * @Description
 * @Version 1.0
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserBalanceService balanceService;

    @Log
    @PostMapping("/topUp/{amount}")
    public ResultInfo topUp(@PathVariable("amount") long amount, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Long balance = null;
        try {
            balance = balanceService.topUp(amount, token);
        } catch (TokenException e) {
            return ResultUtils.failureInfo(e.getTokenStatus());
        } catch (APIException e) {
            return ResultUtils.failureInfo(e.getResultStatus());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.failureInfo(e.getMessage());
        }
        return ResultUtils.successInfo(balance);
    }

    @Log
    @GetMapping("/balance")
    public ResultInfo getBalance(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Long balance = null;
        try {
            balance = balanceService.getBalance(token);
        } catch (TokenException e) {
            return ResultUtils.failureInfo(e.getTokenStatus());
        } catch (APIException e) {
            return ResultUtils.failureInfo(e.getResultStatus());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.failureInfo(e.getMessage());
        }
        return ResultUtils.successInfo(balance);
    }

}
